let app = getApp();
let API_URL = app.globalData.API_URL ;
import { getShopDetail, getGoods } from '../../../../request/api';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        lang: null,
        show: false,
        customStyle: '',
        overlayStyle: '',
        postId: 0,
        isLike: false,
        shopDetailed: {},
        productList: [],
        info: {},
        totalPrice: 0, // 总价
        cartNum: 0, // 购物车数量
        
        // 分页
        pageNo: 1,
        totalPage: 0,
    },

    /**
     * My Function
     */
    // 获取内容
    getPost() {
        let postId = this.data.postId
        let data = { postId }
        getShopDetail(res => {
            if (res.statusCode == 200) {
                if (res.data.favorite != null) {
                    this.setData({ isLike: true })
                }
                this.setData({ shopDetailed: res.data })
                this.requestGetGoods();
            }
        }, data);
        
    },

    // 获取产品
    requestGetGoods() {
        let shop_id = this.data.postId
        let status = 1
        let goodsData = { shop_id, status, pageNo : this.data.pageNo }
        getGoods(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                this.setData({ productList: this.data.productList.concat(request), totalPage : res.data.totalPage })
            }
        }, goodsData);
    },

    // 收藏
    onLike() {
        let user_id = wx.getStorageSync('uid')
        if (!user_id) {
            app.login()
            return
        }
        let data = { target_id: parseInt(this.data.postId, 10), type: 13 }

        if(this.data.isLike) {
            let data = { postId: this.data.shopDetailed.favorite.id }
            wx.request({
                url: `${API_URL}/favoritesDestroy`,
                data: data,
                header: app.header(),
                method: 'post',
                success: res=> {
                    if(res.statusCode == 200) {
                        this.setData({ isLike: false })
                        wx.showToast({
                            title: 'ok',
                            duration: 2000
                        })
                    }
                }
            })
        } else {
            wx.request({
                url: `${API_URL}/favorites`,
                data: data,
                header: app.header(),
                method: 'post',
                success: res=> {
                    if(res.statusCode == 200) {
                        let favorite = {
                            id : res.data.insertId
                        }
                        let detailed = this.data.shopDetailed
                        detailed.favorite = favorite
                        this.setData({ isLike: true, shopDetailed: detailed })
                        wx.showToast({
                            title: 'ok',
                            duration: 2000
                        })
                    }
                }
            })
        }
    },

    // 打电话联系
    onContact() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopDetailed.phoneNum,
            fail: cancel => {
                console.log("cancel: ", cancel);
            }
        })
    },

    // 产品详细
    bottom_alert(e) {
        this.setData({ info: e.currentTarget.dataset.item })
        this.setData({ show: true })
    },

    // 关闭产品详细
    close() {
        this.setData({ show: false })
    },

    // 预览图
    preview(event) {
        let src = event.currentTarget.dataset.src.fullUrl;
        let previewImage = this.data.shopDetailed.images;
        let urls = []
        for (let item of previewImage) {
            urls.push(item.fullUrl)
        }
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: urls // 需要预览的图片http链接列表
        })
    },

    // 产品预览图
    goodsPreview(item) {
        let src = item.currentTarget.dataset.src.fullUrl;
        let imageArrList = []
        for (let imageArr of item.currentTarget.dataset.list) {
            imageArrList.push(imageArr.fullUrl)
        }
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imageArrList// 需要预览的图片http链接列表
        })
    },

    // 跳转高德地图
    goMap() {
        wx.openLocation({
            longitude: parseFloat(this.data.shopDetailed.longitude),
            latitude: parseFloat(this.data.shopDetailed.latitude),
            scale: 18,
            name: this.data.shopDetailed.name_zh,
            address: this.data.shopDetailed.address_zh
        })
    },

    // 结算付款
    settlement(){
        let activeFood = [];
        if(this.data.cartNum == 0)return;
        for(let item of this.data.productList) {
            if(item.num > 0) {
                activeFood.push(item);
            }
        }

        wx.navigateTo({
            url: '/pages/home/shop/orderDetailed/orderDetailed?activeFood=' + JSON.stringify(activeFood)
        });
    },

    // 购物车加入饭菜
    foodPuls(e){
        let foodData = this.data.productList;
        let totalPrice = this.data.totalPrice;
        let cartNum = this.data.cartNum;
        for(let item of foodData){
            if(item.id == e.currentTarget.dataset.item){
                item.num ++;
                cartNum ++;
                totalPrice += parseFloat(item.price);
            }
        }
        this.setData({ productList: foodData, totalPrice: totalPrice, cartNum: cartNum })
    },

    // 购物车减去
    foodSubtract(e) {
        let foodData = this.data.productList;
        let totalPrice = this.data.totalPrice;
        let cartNum = this.data.cartNum;
        for(let item of foodData){
            if(item.id == e.currentTarget.dataset.item){
                item.num --;
                cartNum --;
                totalPrice -= parseFloat(item.price);
            }
        }
        this.setData({ productList: foodData, totalPrice: totalPrice, cartNum: cartNum })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({ lang: app.globalData.lang, navTitle: "shopInfo", navigation: true, postId: options.itemId })
        this.getPost()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if(this.data.pageNo == this.data.totalPage || this.data.totalPage == 0) return
        let pageNo = this.data.pageNo += 1
        this.setData({pageNo : pageNo})
        this.requestGetGoods();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    /**
     * 朋友圈分享
     */
    onShareTimeline: function () {
        return {
            imageUrl: `${this.data.shopDetailed.images[0].fullUrl}`,
            title: `${ this.data.lang.dir == "rtl" ? this.data.shopDetailed.name_ug : this.data.shopDetailed.name_zh }`,
            path: '/pages/home/shop/shopDetailed/shopDetailed?postId=' + this.data.postId
        }
    }
})